import IController from "../Interface/IController";
import IMsgFilter from "../Interface/IMsgFilter";
import NewWorkManager from "../Service/webSocket/NewWorkManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MessageManager {
    private static _instance: MessageManager = null;

    private _msgFilterList: Map<string, IMsgFilter> = new Map();
    private _ctrlList: Map<string, IController> = new Map();

    public static get instance() {
        if (this._instance === null) {
            this._instance = new this();
        }
        return this._instance;
    }

    constructor() {
        // super();
        // this._msgFilterList = new Map<string, IMsgFilter>();
        // this._ctrlList = new Map<string, IController>();
    }

    public onMsg(msgID: number, buf: any): void {
        let ret = null;
        let list = Array.from(this._msgFilterList.keys());
        for (let i = 0; i < list.length; i++) {
            const key = list[i];
            if (key) {
                const msgFilter = this._msgFilterList.get(key);
                if (msgFilter) {
                    ret = msgFilter.onFilterMessage(msgID, buf);
                    if (ret) break;
                }
            }
        }

        if (ret) {
            list = Array.from(this._ctrlList.keys());
            for (let i = 0; i < list.length; i++) {
                const key = list[i];
                if (key) {
                    const ctrl = this._ctrlList.get(key);
                    if (ctrl) {
                        ctrl.onCtrlMessage(msgID, buf);
                    }
                }
            }
        }
    }

    public registerMsgFilter(name: string, msgFilter: IMsgFilter) {
        this._msgFilterList.set(name, msgFilter);
    }

    public unregisterMsgFilter(name: string) {
        this._msgFilterList.delete(name);
    }

    public registerController(name: string, ctrl: IController) {
        this._ctrlList.set(name, ctrl);
    }

    public unregisterController(name: string) {
        this._ctrlList.delete(name);
    }

    public send(data: string) {
        NewWorkManager.instance.send(data);
    }

    public close() {
        NewWorkManager.instance.close();
    }
}